package com.ckd.flyingtrip.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.constants.BaseUserInfo;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.javabean.CityBean;
import com.ckd.flyingtrip.javabean.CityZcBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.GetJsonDataUtil;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisteredActivity extends BaseActivity {

    @BindView(R.id.toolber_color_title)
    TextView title;
    @BindView(R.id.activity_registered_phone)
    EditText phone;
    @BindView(R.id.activity_registered_code)
    TextView code;
    @BindView(R.id.activity_registered_codeText)
    EditText codeText;
    @BindView(R.id.activity_registered_password1)
    EditText password1;
    @BindView(R.id.activity_registered_password2)
    EditText password2;
    @BindView(R.id.activity_registered_btn)
    TextView btn;
    @BindView(R.id.activity_registered_ll)
    LinearLayout linearLayout;
    @BindView(R.id.activity_registered_city)
    LinearLayout city;
    @BindView(R.id.activity_registered_cityText)
    TextView cityText;

    private MyCountDownTimer timer;

    private OptionsPickerView pickerView;
    private ArrayList<String> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> ids = new ArrayList<>();

    private String userArea = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registered);
        ButterKnife.bind(this);

        initView();
        initListener();

    }

    private void initView() {
        timer = new MyCountDownTimer(60000, 1000);
        switch (getIntent().getStringExtra("title")) {
            case "注册":
                title.setText("注册");
                btn.setText("注册");
                linearLayout.setVisibility(View.VISIBLE);
                city.setVisibility(View.VISIBLE);
                initCity();
                break;
            case "忘记密码":
                title.setText("忘记密码");
                btn.setText("找回密码");
                linearLayout.setVisibility(View.INVISIBLE);
                city.setVisibility(View.GONE);
                break;
        }
    }

    private void initCity() {
        String JsonData = new GetJsonDataUtil().getJson(this, "cityzc.json");
        CityZcBean bean = new Gson().fromJson(JsonData, CityZcBean.class);
        for (int i = 0; i < bean.getProvinces().size(); i++) {
            options1Items.add(bean.getProvinces().get(i).getName());
            ArrayList<String> itmes = new ArrayList<>();
            ArrayList<String> num = new ArrayList<>();
            for (int j = 0; j < bean.getProvinces().get(i).getCities().size(); j++) {
                itmes.add(bean.getProvinces().get(i).getCities().get(j).getName());
                num.add(bean.getProvinces().get(i).getCities().get(j).getCode().length() == 4 ?
                        bean.getProvinces().get(i).getCities().get(j).getCode() + "00" : bean.getProvinces().get(i).getCities().get(j).getCode());
            }
            options2Items.add(itmes);
            ids.add(num);
        }
        initPickerView();
    }

    private void initPickerView() {
        pickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                cityText.setText(options2Items.get(options1).get(options2));
                userArea = ids.get(options1).get(options2);
            }
        }).setTitleText("城市选择")
                .setContentTextSize(20)
                .setDividerColor(Color.LTGRAY)
                .setSelectOptions(0, 1)
                .setBgColor(Color.BLACK)
                .setTitleBgColor(Color.DKGRAY)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.YELLOW)
                .setSubmitColor(Color.YELLOW)
                .setTextColorCenter(Color.LTGRAY)
                .isRestoreItem(true)
                .isCenterLabel(false)
                .setLabels("", "", "")
                .setOutSideColor(0x00000000)
                .build();
        pickerView.setPicker(options1Items, options2Items);
    }

    private void initListener() {

    }

    @OnClick({R.id.toolber_color_back, R.id.activity_registered_code, R.id.activity_registered_pact, R.id.activity_registered_btn,
            R.id.activity_registered_city})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolber_color_back:
                finish();
                break;
            case R.id.activity_registered_code:
                if (!Tools.isPhoneNumber(phone.getText().toString().trim())) {
                    toast("手机号输入不正确！");
                    return;
                }
                initCode();
                break;
            case R.id.activity_registered_pact:
                startAction(UserLogInProtocolActivity.class);
                break;
            case R.id.activity_registered_city:
                pickerView.show();
                break;
            case R.id.activity_registered_btn:
                if (!Tools.isPhoneNumber(phone.getText().toString().trim())) {
                    toast("手机号输入不正确！");
                    return;
                }
                if (codeText.getText().toString().trim().equals("")) {
                    toast("请输入验证码！");
                    return;
                }
                if (password1.getText().toString().trim().length() < 7 || password1.getText().toString().trim().length() > 17) {
                    toast("密码位数不正确！");
                    return;
                }
                if (!password1.getText().toString().trim().equals(password2.getText().toString().trim())) {
                    toast("两次密码输入的不一致！");
                    return;
                }
                switch (getIntent().getStringExtra("title")) {
                    case "注册":
                        if (userArea.equals("")) {
                            toast("请选择注册城市！");
                            return;
                        }
                        initCityJudge();
                        break;
                    case "忘记密码":
                        initBtn1();
                        break;
                }
                break;
        }
    }

    private void initCityJudge() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.judgerentcarservice, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("注册城市判断", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        String data = json.getString("data");
                        String openStateElectricity = new JSONObject(data).getString("openStateElectricity");
                        String openStateRentcar = new JSONObject(data).getString("openStateRentcar");
                        if (openStateElectricity.equals("0") && openStateRentcar.equals("0")) {
                            toast("改城市暂未开放！");
                            return;
                        }
                        initBtn();
                    } else {
                        Tools.toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userArea", userArea);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initBtn1() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.forgetpassword, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("忘记密码", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        finish();
                        Tools.toast(msg);
                    } else {
                        Tools.toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userPhone", phone.getText().toString().trim());
                    json_url.put("password", password1.getText().toString().trim());
                    json_url.put("messageCode", codeText.getText().toString().trim());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initBtn() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.ZHUCE, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("注册", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        Tools.toast(msg);
                        finish();
                    } else {
                        Tools.toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userPhone", phone.getText().toString().trim());
                    json_url.put("userPassword", password1.getText().toString().trim());
                    json_url.put("messageCode", codeText.getText().toString().trim());
                    json_url.put("userArea", userArea);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initCode() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.PHONESMS, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("发送手机验证码", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        Tools.toast(msg);
                        timer.start();
                    } else {
                        Tools.toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userPhone", phone.getText().toString().trim());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            code.setClickable(false);
            code.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            code.setClickable(true);
            code.setText("重新获取");
        }
    }

}
